package cease.console;

import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import cease.vo.Butter;
import cease.vo.Message;
import cease.vo.UploadedPhoto;

/**
 * @author dhf
 */
public class PrintHelper {
    private static Pattern p = Pattern.compile("<a.*?>(.*?)</a>",
            Pattern.CASE_INSENSITIVE);

    private static String fineSource(String source) {
        source = StringUtils.trimToEmpty(source);
        Matcher m = p.matcher(source);
        if (m.matches()) {
            return StringUtils.trimToEmpty(m.group(1));
        } else {
            return source;
        }
    }

    public static void printButter(Collection<Butter> butters) {
        if (null == butters || butters.size() <= 0) {
            System.out.println(".");
        } else {
            List<Butter> blist = (List<Butter>) butters;
            for (int i = blist.size() - 1; i >= 0; i--) {
                Butter b = blist.get(i);
                printButter(b);
            }
        }
    }

    public static void printButter(Butter butter) {
        if (null == butter) {
            System.out.println(".");
        } else {
            System.out.println(butter.getUser().getNickName()
                    + ":\t"
                    + butter.getText()
                    + "\n\t"
                    + TimeUtil.compareNow(Long.parseLong(butter
                            .getCreatedTime())) + " 来自 "
                    + fineSource(butter.getSource()) + " (id: "
                    + butter.getId() + ")");
        }
    }

    public static void printUploadedPhoto(UploadedPhoto up) {
        if (null == up) {
            System.out.println(".");
        } else {
            System.out.println("url:\t" + up.getOriginalURL());
        }
    }

    public static void printMessage(Collection<Message> messages) {
        if (null == messages || messages.size() <= 0) {
            System.out.println(".");
        } else {
            List<Message> mlist = (List<Message>) messages;
            for (int i = mlist.size() - 1; i >= 0; i--) {
                Message m = mlist.get(i);
                printMessage(m);
            }
        }
    }

    public static void printMessage(Message message) {
        if (null == message) {
            System.out.println(".");
        } else {
            System.out.println(message.getSender().getNickName()
                    + ":\t"
                    + message.getText()
                    + "\n\t"
                    + TimeUtil.compareNow(Long.parseLong(message
                            .getCreated_at())) + " (id: " + message.getId()
                    + ")");
        }
    }
}
